﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using GPSTrackingWebsiteManager.ClassManager;
using System.Data;
using System.IO;

namespace GPSTrackingWebsiteManager.Manager.Pages
{
    public partial class StockCategories : ClassManager.SessionManagerPage
    {
      
        protected void Page_Load(object sender, EventArgs e)
        {
           
        }

        public string GetPathImage()
        {
            return "../../PointOfSale/CategoryItems/" + getSessionManager().GUID + "/";
        }

        public string GetPathToCreate()
        {
            return "../../PointOfSale/CategoryItems/" + getSessionManager().GUID;
        }

        public string GetPathImage(string imageUrl)
        {
            if (System.IO.File.Exists(Server.MapPath("../../PointOfSale/CategoryItems/" + getSessionManager().GUID + "/" + imageUrl)))
                return "../../PointOfSale/CategoryItems/" + getSessionManager().GUID + "/" + imageUrl;
            else
                return "../../Template/Icons/24px/image-up-icon.png";
        }
        
        protected void lbClearFilters_Click(object sender, EventArgs e)
        {
            StockCategoriesGrid.MasterTableView.FilterExpression = string.Empty;

            foreach (GridColumn column in StockCategoriesGrid.MasterTableView.RenderColumns)
            {
                if (column is GridBoundColumn)
                {
                    GridBoundColumn boundColumn = column as GridBoundColumn;
                    boundColumn.CurrentFilterValue = string.Empty;
                }
            }
            StockCategoriesGrid.MasterTableView.Rebind();
            ResizeGrid();
        }

        private void ResizeGrid()
        {
            decimal Height = Convert.ToDecimal(HiddenFieldHeight.Value) ;
            decimal Width = Convert.ToDecimal(HiddenFieldWidth.Value)/2;

            StockCategoriesGrid.Height = Unit.Parse(Convert.ToString(Height));
            StockCategoriesGrid.Width = Unit.Parse(Convert.ToString(Width));
            StockCategoriesGridTree.Height = Unit.Parse(Convert.ToString(Height));
            StockCategoriesGridTree.Width = Unit.Parse(Convert.ToString(Width));
        }
  
        protected void lbShowError_Click(object sender, EventArgs e)
        {
            ShowErrorMessage(HiddenFieldError.Value);
        }

        public void ShowErrorMessage(string msg)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "objWindowsMessageManager.show_Error", "objWindowsMessageManager.show_Error('" + msg + "','Categorías ...');", true);
        }

        public void ShowInfoMessage(string msg)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "objWindowsMessageManager.show_Info", "objWindowsMessageManager.show_Info('" + msg + "','Categorías ...');", true);
        }

        public void ShowWarningMessage(string msg)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "objWindowsMessageManager.show_Warning", "objWindowsMessageManager.show_Warning('" + msg + "','Categorías ...');", true);
        }

        protected SessionManager getSessionManager()
        {
            return (SessionManager)HttpContext.Current.Session["SessionManager"];
        }

        protected void StockCategoriesGrid_ItemCommand(object sender, GridCommandEventArgs e)
        {
            ResizeGrid();
        }

        protected void StockCategoriesGridTree_ItemCommand(object sender, GridCommandEventArgs e)
        {
            Telerik.Web.UI.RadTreeView tree;

            switch(e.CommandName){
                case "ExpandAllNodes":
                    tree = StockCategoriesGridTree.Items[0].FindControl("StockCategoriesGridTreeView") as Telerik.Web.UI.RadTreeView;
                    tree.ExpandAllNodes();
                    break;

                case "CollapseAllNodes":
                    tree = StockCategoriesGridTree.Items[0].FindControl("StockCategoriesGridTreeView") as Telerik.Web.UI.RadTreeView;
                    tree.CollapseAllNodes();
                    break;

                case "ClearSelectionNodes":
                    tree = StockCategoriesGridTree.Items[0].FindControl("StockCategoriesGridTreeView") as Telerik.Web.UI.RadTreeView;
                    tree.ClearSelectedNodes();
                    GetStockCategoriesByParent(null);
                    break;
                case "DeleteNodeSelected":
                    DeleteNodeSelected();
                    break;
            }
            //ResizeGrid();
        }

        protected void DeleteNodeSelected() {

            

        }

        protected void StockCategoriesGrid_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
        {
            int? parentStockCategoryId = null;
            if(StockCategoriesGridTree.Items.Count > 0){
                Telerik.Web.UI.RadTreeView treeView = StockCategoriesGridTree.Items[0].FindControl("StockCategoriesGridTreeView") as Telerik.Web.UI.RadTreeView;
                if(treeView.SelectedNode != null)
                    parentStockCategoryId = int.Parse(treeView.SelectedNode.Value);
            }

            StockCategoriesGrid.DataSource = GPSTrackingDBV2Custom.Data.DataRepository.StockCategoriesProvider.GetByParentStockCategoryId(getSessionManager().CompanyIDSelectedComboBox, parentStockCategoryId);
            ResizeGrid();
        }

        protected void StockCategoriesGridTree_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
        {
            StockCategoriesGridTree.DataSource = new String[] { "Tree" };
        }

        private void BuildStockCategoriesTree(string name)
        {
            Telerik.Web.UI.RadTreeView treeView = StockCategoriesGridTree.Items[0].FindControl("StockCategoriesGridTreeView") as Telerik.Web.UI.RadTreeView;
            
            System.Data.DataTable dt = GPSTrackingDBV2Custom.Data.DataRepository.StockCategoriesProvider.GetAllByCompanyID(getSessionManager().CompanyIDSelectedComboBox, name);

            treeView.DataTextField = "Name";
            treeView.DataValueField = "ImageUrl";
            treeView.DataFieldID = "StockCategoryID";
            treeView.DataFieldParentID = "ParentStockCategoryID";
            
            treeView.DataSource = dt;
            treeView.DataBind();

        }

        protected void StockCategoriesGridTreeView_NodeDataBound(object sender, Telerik.Web.UI.RadTreeNodeEventArgs e)
        {
            e.Node.ImageUrl = GetPathImage((e.Node.DataItem as System.Data.DataRowView)["ImageUrl"].ToString());
            e.Node.Value = (e.Node.DataItem as System.Data.DataRowView)["StockCategoryID"].ToString();
        }

        public System.Drawing.Image ResizeImageFixedWidth(System.Drawing.Image imgToResize)
        {
            int stockCategorySize = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["StockCategoryImageSize"]);
            int destWidth = stockCategorySize;
            int destHeight = stockCategorySize;

            Bitmap b = new Bitmap(destWidth, destHeight);
            Graphics g = Graphics.FromImage((System.Drawing.Image)b);
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;

            g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
            g.Dispose();

            return (System.Drawing.Image)b;
        }

        protected void StockCategoriesGrid_InsertCommand(object sender, GridCommandEventArgs e)
        {
            GPSTrackingDBV2.Entities.StockCategories stockCategoryEntity = new GPSTrackingDBV2.Entities.StockCategories();
            GPSTrackingDBV2.Entities.StockCategoriesByCompanies stockCategoriesByCompaniesEntity = new GPSTrackingDBV2.Entities.StockCategoriesByCompanies();
            GPSTrackingDBV2.Entities.StockCategoriesLog stockCategoryLogEntity = new GPSTrackingDBV2.Entities.StockCategoriesLog();
            Telerik.Web.UI.RadTreeView treeView;

            DateTime dateTransaction = DateTime.Now;
            Int64 tick = TickManager.TickManager.GetTick(dateTransaction);
            string typeUserTransaction = "";
            string usernameTransaction = "";
            int companyId = getSessionManager().CompanyIDSelectedComboBox;
            string path;

            GPSTrackingDBV2.Data.TransactionManager tm = GPSTrackingDBV2.Data.DataRepository.Provider.CreateTransaction();

            int? parentStockCategoryId = null;
            if (StockCategoriesGridTree.Items.Count > 0)
            {
                treeView = StockCategoriesGridTree.Items[0].FindControl("StockCategoriesGridTreeView") as Telerik.Web.UI.RadTreeView;
                if (treeView.SelectedNode != null)
                {
                    parentStockCategoryId = int.Parse(treeView.SelectedNode.Value);
                    if (GPSTrackingDBV2.Data.DataRepository.StockProvider.GetByCompanyIdStockCategoryId(companyId, parentStockCategoryId).Count > 0)
                    {
                        ShowWarningMessage("No se puede registrar una categoría porque existen productos asociados a la categoría seleccionada.");
                        return;
                    }
                }
            }



            try
            {
                tm.BeginTransaction();


                stockCategoryEntity.StockCategoryId = GPSTrackingDBV2Custom.Data.DataRepository.StockCategoriesProvider.GetNextID();
                stockCategoryEntity.Name = (e.Item.FindControl("txtName") as RadTextBox).Text;
                stockCategoryEntity.ParentStockCategoryId = parentStockCategoryId;
                stockCategoryEntity.LastTick = tick;

                GridEditFormInsertItem insertItem = e.Item as GridEditFormInsertItem;
                RadAsyncUpload radUpload = e.Item.FindControl("RadAsyncUploadImage") as RadAsyncUpload;
                if (radUpload.UploadedFiles.Count > 0)
                {
                    stockCategoryEntity.ImageUrl = radUpload.UploadedFiles[0].FileName;

                    path = GetPathToCreate();

                    if (!System.IO.Directory.Exists(Server.MapPath(path)))
                    {
                        System.IO.Directory.CreateDirectory(Server.MapPath(path));

                        //Set Write Mode
                        System.Security.AccessControl.DirectorySecurity directorySecurity = System.IO.Directory.GetAccessControl(Server.MapPath(path));
                       directorySecurity.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule("Everyone", System.Security.AccessControl.FileSystemRights.FullControl, System.Security.AccessControl.AccessControlType.Allow));
                       System.IO.Directory.SetAccessControl(Server.MapPath(path), directorySecurity);

                    }

                    //radUpload.UploadedFiles[0].SaveAs(Server.MapPath(GetPathImage() + stockCategoryEntity.ImageUrl));

                    byte[] bytes = new byte[radUpload.UploadedFiles[0].ContentLength];
                    radUpload.UploadedFiles[0].InputStream.Read(bytes, 0, Convert.ToInt32(radUpload.UploadedFiles[0].ContentLength));
                    MemoryStream ms = new MemoryStream(bytes);

                    var image = System.Drawing.Image.FromStream(ms);
                    using (Bitmap tempImage = new Bitmap(image))
                    {
                        var newImage = ResizeImageFixedWidth(image);
                        newImage.Save(Server.MapPath(GetPathImage() + stockCategoryEntity.ImageUrl));
                    }

                }

                GPSTrackingDBV2.Data.DataRepository.StockCategoriesProvider.Insert(tm, stockCategoryEntity);

                stockCategoriesByCompaniesEntity.CompanyId = companyId;
                stockCategoriesByCompaniesEntity.StockCategoryId = stockCategoryEntity.StockCategoryId;

                GPSTrackingDBV2.Data.DataRepository.StockCategoriesByCompaniesProvider.Insert(tm, stockCategoriesByCompaniesEntity);

                stockCategoryLogEntity.StockCategoryId = stockCategoryEntity.StockCategoryId;

                stockCategoryLogEntity.TransactionDate = dateTransaction;
                stockCategoryLogEntity.Tick = tick;
                stockCategoryLogEntity.SyncTransaction = "I";

                if (getSessionManager().IsUser)
                {
                    typeUserTransaction = "U";
                    usernameTransaction = getSessionManager().Username;
                }
                if (getSessionManager().IsAdmin)
                {
                    typeUserTransaction = "A";
                    usernameTransaction = getSessionManager().AdminUsername;
                }
                if (getSessionManager().IsMaster)
                {
                    typeUserTransaction = "M";
                    usernameTransaction = getSessionManager().MasterUsername;
                }

                stockCategoryLogEntity.TypeUserTransaction = typeUserTransaction;
                stockCategoryLogEntity.CompanyIdTransaction = companyId;
                stockCategoryLogEntity.UsernameTransaction = usernameTransaction;

                stockCategoryLogEntity.Name = stockCategoryEntity.Name;
                stockCategoryLogEntity.ImageUrl = stockCategoryEntity.ImageUrl;
                stockCategoryLogEntity.ParentStockCategoryId = stockCategoryEntity.ParentStockCategoryId;

                GPSTrackingDBV2.Data.DataRepository.StockCategoriesLogProvider.Insert(tm, stockCategoryLogEntity);

                if (StockCategoriesGridTree.Items.Count > 0)
                {
                    treeView = StockCategoriesGridTree.Items[0].FindControl("StockCategoriesGridTreeView") as Telerik.Web.UI.RadTreeView;

                    Telerik.Web.UI.RadTreeNode menuItem = new Telerik.Web.UI.RadTreeNode();
                    menuItem.ImageUrl = GetPathImage(stockCategoryEntity.ImageUrl);
                    menuItem.Text = stockCategoryEntity.Name;
                    menuItem.Value = stockCategoryEntity.StockCategoryId.ToString();

                    if (treeView.SelectedNode != null){    
                        treeView.SelectedNode.Nodes.Add(menuItem);
                    }
                    else {
                        treeView.Nodes.Add(menuItem);
                    }
                }
                
                tm.Commit();
                GetStockCategoriesByParent(parentStockCategoryId);
                //StockCategoriesGridTree.MasterTableView.Rebind();
                ResizeGrid();
            }
            catch (Exception ex)
            {
                tm.Rollback();
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
                ShowErrorMessage("No se puede insertar la información.");
            }
        }

        protected void StockCategoriesGrid_UpdateCommand(object sender, GridCommandEventArgs e)
        {
            GPSTrackingDBV2.Entities.StockCategories stockCategoryEntity = new GPSTrackingDBV2.Entities.StockCategories();
            GPSTrackingDBV2.Entities.StockCategoriesLog stockCategoryLogEntity = new GPSTrackingDBV2.Entities.StockCategoriesLog();
            Telerik.Web.UI.RadTreeView treeView;

            DateTime dateTransaction = DateTime.Now;
            Int64 tick = TickManager.TickManager.GetTick(dateTransaction);
            string typeUserTransaction = "";
            string usernameTransaction = "";
            int companyId = getSessionManager().CompanyIDSelectedComboBox;
            string imageUrl = String.Empty;

            GPSTrackingDBV2.Data.TransactionManager tm = GPSTrackingDBV2.Data.DataRepository.Provider.CreateTransaction();

            try
            {
                tm.BeginTransaction();


                stockCategoryEntity.OriginalStockCategoryId = Convert.ToInt32((e.Item.FindControl("txtStockCategoryId") as RadTextBox).Text);
                stockCategoryEntity.StockCategoryId = Convert.ToInt32((e.Item.FindControl("txtStockCategoryId") as RadTextBox).Text);
                stockCategoryEntity.Name = (e.Item.FindControl("txtName") as RadTextBox).Text;
                if (!string.IsNullOrEmpty((e.Item.FindControl("txtParentStockCategoryId") as RadTextBox).Text ))
                    stockCategoryEntity.ParentStockCategoryId = Convert.ToInt32((e.Item.FindControl("txtParentStockCategoryId") as RadTextBox).Text);
                stockCategoryEntity.LastTick = tick;
                
                RadAsyncUpload radUpload = e.Item.FindControl("RadAsyncUploadImage") as RadAsyncUpload;
                if (radUpload.UploadedFiles.Count > 0)
                {
                    imageUrl = radUpload.ToolTip;
                    stockCategoryEntity.ImageUrl = radUpload.UploadedFiles[0].FileName;
                    radUpload.UploadedFiles[0].SaveAs(Server.MapPath(GetPathImage() + stockCategoryEntity.ImageUrl));
                }
                else
                {
                    stockCategoryEntity.ImageUrl = radUpload.ToolTip;
                }

                GPSTrackingDBV2.Data.DataRepository.StockCategoriesProvider.Update(tm, stockCategoryEntity);

                stockCategoryLogEntity.StockCategoryId = stockCategoryEntity.StockCategoryId;

                stockCategoryLogEntity.TransactionDate = dateTransaction;
                stockCategoryLogEntity.Tick = tick;
                stockCategoryLogEntity.SyncTransaction = "U";

                if (getSessionManager().IsUser)
                {
                    typeUserTransaction = "U";
                    usernameTransaction = getSessionManager().Username;
                }
                if (getSessionManager().IsAdmin)
                {
                    typeUserTransaction = "A";
                    usernameTransaction = getSessionManager().AdminUsername;
                }
                if (getSessionManager().IsMaster)
                {
                    typeUserTransaction = "M";
                    usernameTransaction = getSessionManager().MasterUsername;
                }

                stockCategoryLogEntity.TypeUserTransaction = typeUserTransaction;
                stockCategoryLogEntity.CompanyIdTransaction = companyId;
                stockCategoryLogEntity.UsernameTransaction = usernameTransaction;

                stockCategoryLogEntity.Name = stockCategoryEntity.Name;
                stockCategoryLogEntity.ImageUrl = stockCategoryEntity.ImageUrl;
                stockCategoryLogEntity.ParentStockCategoryId = stockCategoryEntity.ParentStockCategoryId;

                GPSTrackingDBV2.Data.DataRepository.StockCategoriesLogProvider.Insert(tm, stockCategoryLogEntity);

                if (StockCategoriesGridTree.Items.Count > 0)
                {
                    treeView = StockCategoriesGridTree.Items[0].FindControl("StockCategoriesGridTreeView") as Telerik.Web.UI.RadTreeView;

                    if (treeView.SelectedNode != null)
                    {
                        foreach (RadTreeNode node in treeView.SelectedNode.Nodes)
                        {
                            if (node.Value == stockCategoryEntity.StockCategoryId.ToString())
                            {
                                node.ImageUrl = GetPathImage(stockCategoryEntity.ImageUrl);
                                node.Text = stockCategoryEntity.Name;
                                break;
                            }
                        }
                    }
                    else
                    {
                        foreach (RadTreeNode node in treeView.Nodes)
                        {
                            if (node.Value == stockCategoryEntity.StockCategoryId.ToString())
                            {
                                node.ImageUrl = GetPathImage(stockCategoryEntity.ImageUrl);
                                node.Text = stockCategoryEntity.Name;
                                break;
                            }
                        }
                    }
                }

                //No eliminar porque puede ser una imagen compartida
               // if (!String.IsNullOrEmpty(imageUrl))
                //    System.IO.File.Delete(Server.MapPath(GetPathImage(imageUrl)));
                tm.Commit();
                ResizeGrid();
            }
            catch (Exception ex)
            {
                tm.Rollback();
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
                ShowErrorMessage("No se puede actualizar la información.");
            }
        }

        protected void StockCategoriesGrid_DeleteCommand(object sender, GridCommandEventArgs e)
        {
            GPSTrackingDBV2.Entities.StockCategories stockCategoryEntity = new GPSTrackingDBV2.Entities.StockCategories();
            GPSTrackingDBV2.Entities.StockCategoriesLog stockCategoryLogEntity = new GPSTrackingDBV2.Entities.StockCategoriesLog();
            Telerik.Web.UI.RadTreeView treeView;

            DateTime dateTransaction = DateTime.Now;
            Int64 tick = TickManager.TickManager.GetTick(dateTransaction);
            string typeUserTransaction = "";
            string usernameTransaction = "";
            int companyId = getSessionManager().CompanyIDSelectedComboBox;

            GPSTrackingDBV2.Data.TransactionManager tm = GPSTrackingDBV2.Data.DataRepository.Provider.CreateTransaction();

            try
            {
                tm.BeginTransaction();

                GridEditableItem item = e.Item as GridEditableItem;
                Hashtable Entity = new Hashtable();
                item.ExtractValues(Entity);

                stockCategoryEntity.StockCategoryId = int.Parse(Entity["StockCategoryId"].ToString());
                stockCategoryEntity.Name = Entity["Name"].ToString();
                if (Entity["ParentStockCategoryId"] != null)
                    stockCategoryEntity.ParentStockCategoryId = int.Parse(Entity["ParentStockCategoryId"].ToString());
                stockCategoryEntity.LastTick = tick;

                RadTreeNode nodeDeleted = new RadTreeNode();
                bool isPermitToDelete = true;

                if (StockCategoriesGridTree.Items.Count > 0)
                {
                    treeView = StockCategoriesGridTree.Items[0].FindControl("StockCategoriesGridTreeView") as Telerik.Web.UI.RadTreeView;

                    if (treeView.SelectedNode != null)
                    {
                        foreach (RadTreeNode node in treeView.SelectedNode.Nodes)
                        {
                            if (node.Value == stockCategoryEntity.StockCategoryId.ToString())
                            {
                                nodeDeleted = node;
                                stockCategoryEntity.ImageUrl = nodeDeleted.ImageUrl.ToString().Split('/').Last();
                                if (nodeDeleted.Nodes.Count > 0)
                                {
                                    isPermitToDelete = false;
                                }
                                break;
                            }
                        }
                    }
                    else
                    {
                        foreach (RadTreeNode node in treeView.Nodes)
                        {
                            if (node.Value == stockCategoryEntity.StockCategoryId.ToString())
                            {
                                nodeDeleted = node;
                                stockCategoryEntity.ImageUrl = nodeDeleted.ImageUrl.ToString().Split('/').Last();
                                if (nodeDeleted.Nodes.Count > 0)
                                {
                                    isPermitToDelete = false;
                                }
                                break;
                            }
                        }
                    }


                }

                if (!isPermitToDelete)
                {
                    ShowWarningMessage("No se puede eliminar el registro, porque tiene sub categorias asociadas.");
                    return;
                }

                GPSTrackingDBV2.Data.DataRepository.StockCategoriesByCompaniesProvider.Delete(tm, companyId, stockCategoryEntity.StockCategoryId);

                GPSTrackingDBV2.Data.DataRepository.StockCategoriesProvider.Delete(tm, stockCategoryEntity);

                stockCategoryLogEntity.StockCategoryId = stockCategoryEntity.StockCategoryId;

                stockCategoryLogEntity.TransactionDate = dateTransaction;
                stockCategoryLogEntity.Tick = tick;
                stockCategoryLogEntity.SyncTransaction = "D";

                if (getSessionManager().IsUser)
                {
                    typeUserTransaction = "U";
                    usernameTransaction = getSessionManager().Username;
                }
                if (getSessionManager().IsAdmin)
                {
                    typeUserTransaction = "A";
                    usernameTransaction = getSessionManager().AdminUsername;
                }
                if (getSessionManager().IsMaster)
                {
                    typeUserTransaction = "M";
                    usernameTransaction = getSessionManager().MasterUsername;
                }

                stockCategoryLogEntity.TypeUserTransaction = typeUserTransaction;
                stockCategoryLogEntity.CompanyIdTransaction = companyId;
                stockCategoryLogEntity.UsernameTransaction = usernameTransaction;

                stockCategoryLogEntity.Name = stockCategoryEntity.Name;
                stockCategoryLogEntity.ImageUrl = stockCategoryEntity.ImageUrl;
                stockCategoryLogEntity.ParentStockCategoryId = stockCategoryEntity.ParentStockCategoryId;

                GPSTrackingDBV2.Data.DataRepository.StockCategoriesLogProvider.Insert(tm, stockCategoryLogEntity);

                //No eliminar porque puede ser una imagen compartida
                //if (!String.IsNullOrEmpty(stockCategoryEntity.ImageUrl) && stockCategoryEntity.ImageUrl != "image-up-icon.png")
                //    System.IO.File.Delete(Server.MapPath(GetPathImage(stockCategoryEntity.ImageUrl)));

                nodeDeleted.Remove();

                tm.Commit();
            }
            catch (Exception ex)
            {
                tm.Rollback();
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
                ShowErrorMessage("No se puede eliminar la información.");
            }
        }

        protected void StockCategoriesGridTreeView_NodeClick(object sender, RadTreeNodeEventArgs e)
        {
            GetStockCategoriesByParent(int.Parse(e.Node.Value.ToString()));
        }

        protected void GetStockCategoriesByParent(int? parentStockCategoryId)
        {
            StockCategoriesGrid.DataSource = GPSTrackingDBV2Custom.Data.DataRepository.StockCategoriesProvider.GetByParentStockCategoryId(getSessionManager().CompanyIDSelectedComboBox, parentStockCategoryId);
            StockCategoriesGrid.DataBind();
            ResizeGrid();
        }

        protected void StockCategoriesGridTree_DataBound(object sender, EventArgs e)
        {
            BuildStockCategoriesTree("-1");
        }

    }
}